//类别管理
//获取分类信息
function get() {
    $.ajax({
        type: 'GET',
        url: '/my/category/list',
        success: function (res) {
            if (res.status == 0) {
                //用数组可以很好的改善字符串内存占用过多问题
                let arr = []
                res.data.forEach(element => {
                    arr.push(`<tr>
                    <td>${element.name}</td>
                    <td>${element.alias}</td>
                    <td><button id="bian" data-id="${element.id}" data-name="${element.name}" data-alias="${element.alias}" type="button" class="layui-btn layui-btn-xs">编辑</button>
                    <button id="shan" data-id="${element.id}" type="button" class="layui-btn layui-btn-xs layui-btn-danger">删除</button></td>
                </tr>`)
                });
                $('tbody').html(arr.join(""))
            }
        },
        //  //加请求头，否则会提示身份认证失败
        //  headers: {
        //     Authorization: localStorage.getItem('token')
        // },
    })
}
get()
//单击添加类别出现弹出层
let form = layui.form

let index
$('#add').on('click', function () {
    index = layer.open({
        type: 1,
        content: $('#script').html(),
        title: '添加分类',
        area: ['500px', '300px']
    });
})
//添加类别
$('body').on('submit', '.form', function (e) {
    e.preventDefault()
    $.ajax({
        type: 'POST',
        url: '/my/category/add',
        data: $(this).serialize(),
        success: function (res) {
            layer.msg(res.message)
            if (res.status === 0) {
                layer.close(index)
                get()
            }
        }
    })
})
//删除
let id
let layer = layui.layer
$('tbody').on('click', '#shan', function () {
    let id = $(this).data('id')
    layer.confirm('你确定要删除吗', function (x) {
        $.ajax({
            url: '/my/category/delete',
            data: {
                id: id
        },
            success: function (res) {
                layer.msg(res.message)
                if (res.status === 0) {
                    get()
                }
            }
            
        })
        layer.close(x);
    })
})

//编辑  换一个新模板
$('tbody').on('click', '#bian', function () {
    //获取3个data属性值
    data = $(this).data()
    id =data.id
    // console.log(data);
   //单击弹出框
    index = layer.open({
        type: 1,
        content: $('#bianji').html(),
        title: '编辑分类',
        area: ['500px', '300px'],
        //弹层成功后执行success
        success: function () {
            //数据回填
            form.val('aaa',data)
        }
    });
})
//表单提交
$('body').on('submit', '.adc', function (e) {
    e.preventDefault()
    let data ='id'+'='+ id +'&'+ $(this).serialize() 
    console.log(data);
    $.ajax({
        type: 'POST',
        url: `/my/category/update`,
        data: data,
        success:function(res) {
            layer.msg(res.message)
            if (res.status === 0) {
                layer.close(index)
                get()
            }
        }
    })
})